<template>
  <!--
    	作者：offline
    	时间：2018-09-10
    	描述：实物对账
  -->
  <div class="m-view-physicalCheckInfo m-window" id="phyApp" ref="elementId">
    <div class="m-agTable m-bottom">
      <ag-grid-component
        ref="agGridComponent"
        :getColumnDefs="columnDefs"
        :getRowSelection="'single'"
        :tableName="'goodsAccountBill'"
        :getGridOptions="phyGridOptions"
        :getRowData="rowData"
        :isColFit="true"
        :systemInfo="$systemInfo"
        v-loading="loading"
      ></ag-grid-component>
    </div>
  </div>
</template>

<script>
import _Api from "@/api";
import localeText from "@/i18n/agGridText";
// import Vue from "vue";
import buttonLink from "@/components/buttonLink.js";
import gridOptions from "lesso-common/public/gridOptions";
import Msg from "@/public/message.js";
import constant from "@/public/constant";

export default {
  data() {
    return {
      rowData: [],
      columnDefs: [],
      loading: false,
    };
  },
  beforeMount() {
    this.phyGridOptions = Object.assign(
      {
        context: {
          componentParent: this,
        },
        enableColResize: true,
        localeText: localeText,
        enableCellChangeFlash: true,
        enableRangeSelection: true,
        enableFilter: true, //列过滤器
        enableSorting: true, //列排序
        animateRows: true, //排序动画
        //   getContextMenuItems: this.getContextMenuItems
      },
      gridOptions({
        dragSelectCheckbox: true,
        singleSelection: true,
        operation: true,
      })
    );
    let setCellStyle = (pramas) => {
      setTimeout(() => {
        const { retFlag, billState } = pramas.data;
        // 退回的实物对账单行背景变为黄色
        if (retFlag == 1 && billState == 1) {
          return { backgroundColor: "#FFFF00" };
        } else {
          return { backgroundColor: null };
        }
      });
    };
    this.columnDefs = [
      {
        headerName: "实物对账单号",
        field: "gooAccNo",
        width: 170,
        cellRenderer: buttonLink,
        checkboxSelection: true,
        headerCheckboxSelection: true,
        cellStyle: setCellStyle,
      }, //  singleClickEditRenderer
      {
        headerName: "客户",
        field: "companyName",
        width: 200,
        tooltipField: "companyName",
        cellStyle: setCellStyle,
      },
      {
        headerName: "供应商",
        field: "supplierName",
        width: 250,
        tooltipField: "supplierName",
        cellStyle: setCellStyle,
      },
      {
        headerName: "对账金额",
        field: "amount",
        width: 100,
        cellRenderer: function(params) {
          if (params.value)
            return params.value
              .toString()
              .replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
          else return params.value;
        },
        cellStyle: setCellStyle,
      },
      {
        headerName: "单据状态",
        field: "billState",
        width: 100,
        cellStyle: setCellStyle,
        cellRenderer: function(params) {
          if (params.value == "1") return '<span class="ag-icon">保存</span>';
          else if (params.value == "2" && constant.user.userTypeId == "4")
            return '<span class="ag-icon">提交</span>';
          else if (params.value == "2" && constant.user.userTypeId != "4")
            return '<span class="ag-icon">未确认</span>';
          else if (params.value == "3")
            return '<span class="ag-icon">已确认</span>';
          else if (params.value == "4")
            return '<span class="ag-icon">退回</span>';
        },
      },
      {
        headerName: "申请人",
        field: "creator",
        width: 250,
        tooltipField: "creator",
        cellStyle: setCellStyle,
      },
      {
        headerName: "申请日期",
        field: "createDate",
        width: 100,
        cellStyle: setCellStyle,
        cellRenderer: function(params) {
          if (params.value) {
            return new Date(Date.parse(params.value.replace(/-/g, "/"))).Format(
              "yyyy-MM-dd"
            );
          }
        },
      }, //jjc
      {
        headerName: "提交人",
        field: "submitter",
        width: 100,
        cellStyle: setCellStyle,
        tooltipField: "submitter",
      },
      {
        headerName: "提交日期",
        field: "submitDate",
        width: 100,
        cellStyle: setCellStyle,
        cellRenderer: function(params) {
          if (params.value)
            return new Date(Date.parse(params.value.replace(/-/g, "/"))).Format(
              "yyyy-MM-dd"
            );
        },
      },
      {
        headerName: "确认人",
        field: "confirmer",
        width: 100,
        cellStyle: setCellStyle,
      },
      {
        headerName: "确认日期",
        field: "confirmDate",
        width: 100,
        cellStyle: setCellStyle,
        cellRenderer: function(params) {
          if (params.value)
            return new Date(Date.parse(params.value.replace(/-/g, "/"))).Format(
              "yyyy-MM-dd"
            );
        },
      },
    ];
  },
  methods: {
    getContextMenuItems() {
      var that = this;
      var result = [
        {
          name: "单元格复制",
          action: function() {
            that.$refs[
              "agGridComponent"
            ].gridOptions.api.copySelectedRangeToClipboard();
          },
        },
        {
          name: "行复制",
          action: function() {
            that.$refs[
              "agGridComponent"
            ].gridOptions.api.copySelectedRowsToClipboard();
          },
        },
      ];
      return result;
    },
    // 设置表格列
    setColumnDefs() {
      this.$refs["agGridComponent"].gridOptions.api.setColumnDefs(
        this.columnDefs
      );
    },
    getDataRows(msg) {
      this.$refs["agGridComponent"].gridOptions.api.setRowData(msg);
      // let allColumnIds = [];
      // this.phyGridOptions.columnApi.getAllColumns().forEach(function(column) {
      // 	allColumnIds.push(column.colId);
      // });
      //this.phyGridOptions.columnApi.autoSizeColumns(allColumnIds);
    },
    getSelectedRow() {
      var row = this.$refs["agGridComponent"].gridOptions.api.getSelectedRows();
      if (row.length <= 0) {
        Msg.showPopMsg("提示：请选择需要删除的数据");
        return;
      }
      if (row[0].billState > 1) {
        Msg.showPopMsg("提示：当前单据不允许删除，请重新选择！");
        return;
      }
      var that = this;
      this.$confirm("是否确认删除该数据？", "消息提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        distinguishCancelAndClose: true,
      }).then(() => {
        var id = "";
        for (var i = 0; i < row.length; i++) {
          id += row[i].id + ",";
        }
        id = id.substr(0, id.length - 1);
        var obj = {
          dataType: 1,
          id: id,
          modifyer: this.$global.user.loginName,
          modifyerId: this.$global.user.id,
          state: 1,
        };
        _Api
          .delAccountListSelectedInfo(obj)
          .then(function(response) {
            var data = response.data;
            if (data.code == "1") {
              Msg.showSuccessMsg("操作成功");
              that.$refs["agGridComponent"].girdOptions.api.updateRowData({
                remove: row,
              });
            } else {
              Msg.showErrorMsg(data.info);
            }
          })
          .catch((err) => {
            Msg.showErrorMsg(err.data.message);
          });
      });
    },
    setClickValue(value) {
      this.$emit("getClickValue", value.data);
    },
  },
  mounted() {
    // this.$refs['agGridComponent'].gridOptions.api.hideOverlay();
    var userTypeId = this.$global.user.userTypeId;
    if (userTypeId) {
      if (userTypeId == 4) {
        //供应商
        this.columnDefs.splice(2, 1); //不显示供应商列 jjc
        //this.columnDefs.splice(3,1);
      } else {
        this.columnDefs.splice(1, 1); //不显示公司列
        //this.columnDefs.splice(2,1);
      }
    }
  },
};

function singleClickEditRenderer() {}
singleClickEditRenderer.prototype.init = function(params) {
  var template =
    '<span><button id="theValue" class="rendererClass">' +
    params.value +
    "</button></span>";
  var tempDiv = document.createElement("div");
  tempDiv.innerHTML = template;
  this.eGui = tempDiv.firstElementChild;

  this.params = params;
  this.eValue = this.eGui.querySelector("#theValue");
  this.eValue.innerHTML = params.value;
  // this.eButton = this.eGui.querySelector("#theButton");
  this.buttonClickListener = this.onButtonClicked.bind(this);
  this.eValue.addEventListener("click", this.buttonClickListener);
};

singleClickEditRenderer.prototype.onButtonClicked = function(event) {
  // var value =this.params.value;
  //	phyApp[1].__vue__.setClickValue(this.params.data);
  phyApp.__vue__.setClickValue(this.params.data);
};

singleClickEditRenderer.prototype.createGui = function() {};

singleClickEditRenderer.prototype.getGui = function() {
  return this.eGui;
};

singleClickEditRenderer.prototype.afterGuiAttached = function() {};

singleClickEditRenderer.prototype.destroy = function() {};

singleClickEditRenderer.prototype.isPopup = function() {
  return false;
};

//Date.prototype.Format = function (fmt) {
//  var o = {
//      "M+": this.getMonth() + 1, //月份
//      "d+": this.getDate(), //日
//      "H+": this.getHours(), //小时
//      "m+": this.getMinutes(), //分
//      "s+": this.getSeconds(), //秒
//      "q+": Math.floor((this.getMonth() + 3) / 3), //季度
//      "S": this.getMilliseconds() //毫秒
//  };
//  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
//  for (var k in o)
//  if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
//  return fmt;
//}
</script>
